package com.personal.common.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.personal.common.exception.BusinessException;
import com.personal.common.util.SignatureUtil;
import com.personal.common.util.StringUtils;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class SignInterceptor implements HandlerInterceptor{

	private static final String SIGN_KEY = "26F72780372E84B6CFAED6F7B19139CC47B1912B6CAED753";
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		JSONObject j=new JSONObject();
        try {
            String sign= request.getHeader("G-GENERAL-SIGN");
            String body=request.getParameter("body");
            if (StringUtils.isEmpty(sign)) {
                throw new BusinessException("sign不能为空");
            }
            if (StringUtils.isEmpty(body)){
                throw new BusinessException("body不能为空");
            }
            Map paramMap =new HashMap();
            paramMap.put("body",body);
            if(!SignatureUtil.checkSign(paramMap, SIGN_KEY, sign)){
                throw new BusinessException("签名验证失败");
            }
        } catch (BusinessException e) {
            j.put("success","false");
            j.put("msg",e.getMessage());
            response.getWriter().print(j.toJSONString());
            return false;

        }
        return true;
	}
}
